package com.hunanwenli.service.impl;

import com.alibaba.fastjson.JSON;
import com.hunanwenli.entity.OrderMsg;
import com.hunanwenli.entity.OrderStatus;
import com.hunanwenli.entity.ShopGoods;
import com.hunanwenli.mapper.OrderMsgMapper;
import com.hunanwenli.mapper.OrderStatusMapper;
import com.hunanwenli.mapper.ShopGoodsMapper;
import com.hunanwenli.service.CommodityService;
import com.hunanwenli.service.RedisService;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;

/**
 * @author wanzhenyu
 * @date 2021/6/7 0:07
 */
@Service
@Transactional
@Log4j2
public class CommodityServiceImpl implements CommodityService {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    @Override
    public ShopGoods selectByPrimaryKey(Long seckillId) {
        return shopGoodsMapper.selectByPrimaryKey(seckillId);
    }

    @PostConstruct
    public void regCallback(){
        rabbitTemplate.setConfirmCallback((correlationData,ack,cause)->{
            String jsonObject = correlationData.getId();
            OrderMsg parseObject = JSON.parseObject(jsonObject, OrderMsg.class);
            if (ack && parseObject!=null){
                //修改订单状态冗余表
                OrderStatus orderStatus = new OrderStatus();
                orderStatus.setStatus(1).setOrderId(parseObject.getId()).setUpdateTime(new Date());
                orderStatusMapper.updateByPrimaryOrder(orderStatus);
            }
        });
    }
    @Override
    public void sendMessage(OrderMsg orderMsg){
        //插入订单对应状态的冗余表
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setStatus(-1).setCreateTime(new Date()).setOrderId(orderMsg.getId());
        orderStatusMapper.insert(orderStatus);
        rabbitTemplate.convertAndSend("seckill_exchange","",
                JSON.toJSONString(orderMsg),new CorrelationData(JSON.toJSONString(orderMsg)));
    }

    @Override
    public int insert(ShopGoods record) {
        return shopGoodsMapper.insert(record);
    }

    @Override
    public List<ShopGoods> selectAllGoods() {
        return shopGoodsMapper.selectAllGoods();
    }
}
